package com.cheer.ba.view.fragment;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.footview.CustomerFooter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cheer.ba.R;
import com.cheer.ba.app.oss.OssManager;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.H5Address;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.CheerCircleModel;
import com.cheer.ba.model.CommentModel;
import com.cheer.ba.presenter.impl.CommentPresenter;
import com.cheer.ba.utils.DensityUtils;
import com.cheer.ba.utils.ShareNewsUtil;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.activity.ArticlePublishAty;
import com.cheer.ba.view.activity.CheerCircleDetailAty;
import com.cheer.ba.view.activity.VideoPublishAty;
import com.cheer.ba.view.adapter.CheerCircleAdp;
import com.cheer.ba.view.base.BaseCommFrg;
import com.cheer.ba.widget.ShowPopupView;
import com.cheer.ba.widget.headview.CheerHeadView;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 加油圈
 * Created by Hq on 2017/7/7.
 */
public class CheerCircleFrg extends BaseCommFrg implements ShowPopupView.OnItemPopupClick {

    @BindView(R.id.id_comment_xrefreshv)
    XRefreshView mXRefreshView;
    @BindView(R.id.id_comment_recyclev)
    RecyclerView mRecycleView;
    private CheerCircleAdp mCommentAdp;
    //存储柴油信息
    private List<CheerCircleModel> mCheerCircles = new ArrayList<CheerCircleModel>();

    //弹出头像框
    private ShowPopupView popupView;
    public static final String[] POPUP_ITEMS = {"删除"};
    public static final int[] POPUP_ITEMS_COLOR = {R.color.red};
    private ShowPopupView popupView1;
    public static final String[] POPUP_PUBLISH = {"图文", "小视频"};
    private ShareNewsUtil mShare;
    //记录点赞的item下标
    private int mRecordLikePos;
    //记录点击的item
    private CheerCircleModel mRecordCircleItem;
    //记录删除评论或者回复的model
    private CommentModel mRecordCommentItem;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_comment_list, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new CommentPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return !mCheerCircles.isEmpty();
    }

    @Override
    public void initView() {
        popupView = new ShowPopupView(frg);
        popupView.setItemColor(POPUP_ITEMS_COLOR);
        popupView.setOnItemPopupClick(this);

        popupView1 = new ShowPopupView(frg);
        popupView1.setOnItemPopupClick(new ShowPopupView.OnItemPopupClick() {
            @Override
            public void OnItemClick(int position, String tag) {
                switch (position) {
                    case 0:
                        //图片发布
                        Intent intent = new Intent(frg, ArticlePublishAty.class);
                        intent.putExtra(IntentKey.General.KEY_TYPE, "1");
                        showActivity(frg, intent);
                        break;
                    case 1:
                        //视频发布
                        showActivity(frg, VideoPublishAty.class);
                        break;
                }
            }
        });

        int width = DensityUtils.getScreenW(frg);
        setXRefreshView(mXRefreshView, true, true, false, false, new CheerHeadView(frg), new CustomerFooter(frg));
        mRecycleView.setLayoutManager(new LinearLayoutManager(frg));
        mRecycleView.setHasFixedSize(true);
        mCommentAdp = new CheerCircleAdp(R.layout.adp_cheer_circle, mCheerCircles, width);
//        mCommentAdp.openLoadAnimation(new CustomAnimation());
        mCommentAdp.setNotDoAnimationCount(3);
        mCommentAdp.isFirstOnly(false);
        mRecycleView.setAdapter(mCommentAdp);
        mCommentAdp.setOnSelfChildItemClick(new CheerCircleAdp.onSelfChildItemClick() {
            @Override
            public void onSelfItemClick(CheerCircleModel cheerCircleModel, CommentModel commentModel) {
                if (isLogin(true)) {
                    if (commentModel.delFlag == 0) {
                        mRecordCircleItem = cheerCircleModel;
                        mRecordCommentItem = commentModel;
                        if (TextUtils.equals(Session.getUserId(), commentModel.custId)) {
                            //自己的评论
                            popupView.showAtLocPop(mFrameRoot, POPUP_ITEMS);
                        } else {
                            //回复别人的评论
                            ((CommentPresenter) presenter).showCommentPop(mFrameRoot, "2", "回复 " + commentModel.custNname + "：", true);
                        }
                    }
                }
            }
        });
        setOnRefreshDataListener(new IRefreshPageListener() {
            @Override
            public void refreshPage() {
                if (!hasDataInPage()) {
                    //没有数据
//                    mXRefreshView.startRefresh();
                    loadData(true, false);
                } else {
                    mXRefreshView.startRefresh();
                }
            }
        });

        EventBus.getDefault().register(this);
    }

    @Override
    public void OnItemClick(int position, String tag) {
        //删除评论或者回复
        ((CommentPresenter) presenter).delMyComment(false, mRecordCommentItem.uid);
    }

    @Override
    public void initData() {
        List<CheerCircleModel> mCache = ((CommentPresenter) presenter).getCacheData();
        if (null != mCache && !mCache.isEmpty()) {
            updateViewWithLoadMore(mCache, false, ConstantTag.COMMENT_LIST_SUCCESS);
        } else {
            loadData(true, false);
        }
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                loadData(false, false);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                loadData(false, true);
            }
        });
        mCommentAdp.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CheerCircleModel model = (CheerCircleModel) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.id_jump_circle_detail_rela:
                        //进入详情
                        mRecordLikePos = position;
                        mRecordCircleItem = model;
                        Intent intent = new Intent(frg, CheerCircleDetailAty.class);
                        intent.putExtra(IntentKey.General.KEY_MODEL, model);
                        startActivity(intent);
                        break;
                    case R.id.id_circle_del_txt:
                        //删除
                        mRecordLikePos = position;
                        ((CommentPresenter) presenter).delDynamic(true, model.uid);
                        break;
                    case R.id.id_forward_rela:
                        //转发
                        String context = model.title.replaceAll("<br/>", "");
                        mShare = new ShareNewsUtil(frg, context, "加油省钱？选加油啦错不了！", H5Address.FORWARD_APP + model.webUrl + "?s=true", "");
                        mShare.showShare();
                        break;
                    case R.id.id_circle_like_linear:
                        //点赞
                        if (isLogin(true)) {
                            mRecordLikePos = position;
                            if (model.goodStatus == 1) {
                                //取消点赞
                                ((CommentPresenter) presenter).userDelOperation(true, "4", "12", model.sourceId);
                            } else {
                                //点赞
                                ((CommentPresenter) presenter).userOperation(true, "4", "12", model.sourceId);
                            }
                        }
                        break;
                    case R.id.id_circle_comment_txt:
                        //评论
                        if (isLogin(true)) {
                            mRecordCircleItem = model;
                            ((CommentPresenter) presenter).showCommentPop(mFrameRoot, "1", "评论：", true);
                        }
                        break;
                }
            }
        });
    }

    /**
     * 加载数据
     *
     * @param loadMore 是否加载更多
     */
    public void loadData(boolean isShowLoad, boolean loadMore) {
        ((CommentPresenter) presenter).getDynamicList(loadMore, isShowLoad, Constants.PAGESIZE);
        if (!loadMore) {
            stopRefresh(mXRefreshView, 2000);
        } else {
            stopLoadMore(mXRefreshView, 2000);
        }
    }

    @OnClick(R.id.id_circle_publish_txt)
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_circle_publish_txt:
                //发布按钮
                if (isLogin(true)) {
                    popupView1.showAtLocPop(mFrameRoot, POPUP_PUBLISH);
                }
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.LIKE_SUCCESS)) {
                //点赞成功
                for (int i = 0; i < mCheerCircles.size(); i++) {
                    if (i == mRecordLikePos) {
                        CheerCircleModel model = mCheerCircles.get(i);
                        model.goodStatus = 1;
                        model.goodCount += 1;
                        mCommentAdp.notifyDataSetChanged();
                        break;
                    }
                }
                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, ConstantTag.DEL_LIKE_SUCCESS)) {
                //取消点赞成功
                for (int i = 0; i < mCheerCircles.size(); i++) {
                    if (i == mRecordLikePos) {
                        CheerCircleModel model = mCheerCircles.get(i);
                        model.goodStatus = 0;
                        model.goodCount -= 1;
                        mCommentAdp.notifyDataSetChanged();
                        break;
                    }
                }
                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, "1")) {
                //评论
                String context = (String) t;
                ((CommentPresenter) presenter).userComment(false, context, mRecordCircleItem.sourceType, mRecordCircleItem.sourceId, "");
            } else if (TextUtils.equals(tag, ConstantTag.COMMENT_SUCCESS)) {
                //评论成功
                ToastUtil.showToast("评论成功");
                CommentModel model = (CommentModel) t;
                if (null != model) {
                    if (null != mRecordCircleItem) {
                        model.custId = Session.getUserId();
                        model.custNname = Session.getUserName();
                        model.custImg = Session.getUserPicUrl().replace(OssManager.OSS_HOST, "");
                        List<CommentModel> mComments = mRecordCircleItem.getCommentList();
                        mComments.add(0, model);
                        mCommentAdp.notifyDataSetChanged();
                        mRecordCircleItem = null;
                    }
                } else {
                    mXRefreshView.startRefresh();
                }

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, "2")) {
                //回复
                String context = (String) t;
                ((CommentPresenter) presenter).userReply(false, context, mRecordCircleItem.sourceType, mRecordCircleItem.sourceId, mRecordCommentItem.custId, mRecordCommentItem.uid);
            } else if (TextUtils.equals(tag, ConstantTag.REPLY_SUCCESS)) {
                //回复成功
                ToastUtil.showToast("回复成功");
                CommentModel model = (CommentModel) t;
                if (null != model) {
                    if (null != mRecordCircleItem) {
                        model.custId = Session.getUserId();
                        model.custNname = Session.getUserName();
                        model.custImg = Session.getUserPicUrl().replace(OssManager.OSS_HOST, "");
                        model.replyCustNname = mRecordCommentItem.custNname;
                        model.replyCustImg = mRecordCommentItem.custImg;
                        model.replyCustId = mRecordCommentItem.custId;
                        List<CommentModel> mComments = mRecordCircleItem.commentList;
                        mComments.add(0, model);
                        mCommentAdp.notifyDataSetChanged();
                        mRecordCircleItem = null;
                    }
                }

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, ConstantTag.DEL_COMMENT_SUCCESS)) {
                ToastUtil.showToast("评论删除成功");
                //删除评论或者回复
                if (null != mRecordCircleItem) {
                    List<CommentModel> mComments = mRecordCircleItem.commentList;
                    for (CommentModel model : mComments) {
                        if (TextUtils.equals(model.uid, mRecordCommentItem.uid)) {
                            model.delFlag = 1;
                            mCommentAdp.notifyDataSetChanged();
                            break;
                        }
                    }
                    mRecordCircleItem = null;
                }

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(ConstantTag.DEL_DYNAMIC, tag)) {
                //动态删除
                if (mCheerCircles.size() == 1) {
                    mCheerCircles.clear();
                    mCommentAdp.notifyDataSetChanged();
                    dataStatus(3);
                } else {
                    mCheerCircles.remove(mRecordLikePos);
                    mCommentAdp.notifyDataSetChanged();
                }

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            }
        }
    }

    @Override
    public <T> void updateViewWithLoadMore(T t, boolean loadMore, String tag) {
        if (!loadMore) {
            mCheerCircles.clear();
            mXRefreshView.stopRefresh();
        } else {
            mXRefreshView.stopLoadMore();
        }
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.COMMENT_LIST_SUCCESS)) {
                //柴油批发信息
                List<CheerCircleModel> comments = (List<CheerCircleModel>) t;
                if (!comments.isEmpty()) {
                    if (!loadMore) {
                        mCommentAdp.clearSparse();
                    }
                    mCheerCircles.addAll(comments);
                    mCommentAdp.notifyDataSetChanged();
                } else {
                    if (loadMore) {
                        ToastUtil.showToast(getString(R.string.no_more_data));
                    } else {
                        //没有数据
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        //返回类型
        String type = event.type;
        if (TextUtils.equals(type, ConstantTag.PUBLISH_DYNAMIC)) {
            //发布成功
            mXRefreshView.startRefresh();
        } else if (TextUtils.equals(type, ConstantTag.DEL_DYNAMIC)) {
            //动态删除
            if (mCheerCircles.size() == 1) {
                mCheerCircles.clear();
                mCommentAdp.notifyDataSetChanged();
                dataStatus(3);
            } else {
                mCheerCircles.remove(mRecordLikePos);
                mCommentAdp.notifyDataSetChanged();
            }
        } else if (TextUtils.equals(type, ConstantTag.LIKE_SUCCESS)) {
            //点赞成功
            for (int i = 0; i < mCheerCircles.size(); i++) {
                if (i == mRecordLikePos) {
                    CheerCircleModel model = mCheerCircles.get(i);
                    model.goodStatus = 1;
                    model.goodCount += 1;
                    mCommentAdp.notifyDataSetChanged();
                    break;
                }
            }
        } else if (TextUtils.equals(type, ConstantTag.DEL_LIKE_SUCCESS)) {
            //取消点赞成功
            for (int i = 0; i < mCheerCircles.size(); i++) {
                if (i == mRecordLikePos) {
                    CheerCircleModel model = mCheerCircles.get(i);
                    model.goodStatus = 0;
                    model.goodCount -= 1;
                    mCommentAdp.notifyDataSetChanged();
                    break;
                }
            }
        } else if (TextUtils.equals(type, ConstantTag.COMMENT_SUCCESS)) {
            //评论成功
            CommentModel model = (CommentModel) event.model;

            List<CommentModel> mComments = mRecordCircleItem.getCommentList();
            mComments.add(0, model);
            mCommentAdp.notifyDataSetChanged();
            mRecordCircleItem = null;
        } else if (TextUtils.equals(type, ConstantTag.REPLY_SUCCESS)) {
            //回复成功
            CommentModel model = (CommentModel) event.model;

            List<CommentModel> mComments = mRecordCircleItem.getCommentList();
            mComments.add(0, model);
            mCommentAdp.notifyDataSetChanged();
            mRecordCircleItem = null;
        } else if (TextUtils.equals(type, ConstantTag.DEL_COMMENT_SUCCESS)) {
            //删除评论或者回复
            CommentModel commentModel = (CommentModel) event.model;
            List<CommentModel> mComments = mRecordCircleItem.getCommentList();
            for (CommentModel model : mComments) {
                if (TextUtils.equals(model.uid, commentModel.uid)) {
                    model.delFlag = 1;
                    mCommentAdp.notifyDataSetChanged();
                    break;
                }
            }
            mRecordCircleItem = null;
        } else if (TextUtils.equals(type, ConstantTag.REFRESH_DATA_CIRCLE)) {
            //刷新圈子数据
            mXRefreshView.startRefresh();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(frg).onActivityResult(requestCode, resultCode, data);
    }
}
